package com.websocket.handshake;

import com.websocket.service.WebSocketConnection;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ClientHandshake;
import org.springframework.util.CollectionUtils;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HandshakeExecutionChain {

    List<HandshakeInterceptor> interceptors = new ArrayList<>();

    public HandshakeExecutionChain addInterceptor(HandshakeInterceptor interceptor) {
        interceptors.add(interceptor);
        return this;
    }

    public boolean applyHandle(WebSocketConnection conn, Draft draft, ClientHandshake handshake, Map<Principal, WebSocket> connections) {
        if (CollectionUtils.isEmpty(interceptors)) return true;
        for (HandshakeInterceptor interceptor : interceptors) {
            if (!interceptor.beforeHandshake(conn, draft, handshake, connections)) {
                return false;
            }
        }
        return true;
    }
}
